<?php
declare(strict_types=1);

/**
 * This is my open source code, please do not use it for commercial applications.
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code
 *
 * @author Yuandong<837215079@qq.com>
 * @link   https://github.com/gzydong/hyperf-chat
 */

namespace App\Middleware;

use App\Model\Request;
use App\Support\Response;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Router\Dispatched;
use Hyperf\Utils\Context;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class CorsMiddleware implements MiddlewareInterface
{

    /**
     * @Inject
     * @var RequestInterface
     */
    protected $request;

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = Context::get(ResponseInterface::class);
        $response = $response->withHeader('Access-Control-Allow-Origin', '*')
            ->withHeader('Access-Control-Allow-Credentials', 'true')
            ->withHeader('Access-Control-Allow-Headers', 'DNT,Keep-Alive,User-Agent,Cache-Control,Content-Type,Authorization,lang');

        Context::set(ResponseInterface::class, $response);

        if ($request->getMethod() == 'OPTIONS' || $request->getUri()->getPath() == '/favicon.ico') {
            return $response;
        }

        $rest = $this->request->getAttribute(Dispatched::class)->handler;

        try {
            $data = [
                'route' => $rest->route,
                'params' => json_encode($this->request->all()),
                'headers' => json_encode($this->request->getHeaders()),
                'ip' => get_real_ip(),
                'time'=>time()
            ];

//            $requestId = Request::addRequestLog($data);
//            Context::set('requestId', $requestId);
        }catch (\Exception $e){

        }


        return $handler->handle($request);
    }
}
